<?php

include_once('_path.php');

include_once(_CONST_LOCAL_INCLUDE_PATH."database.class.php");
$database = new Database($db_vars);

include_once(_CONST_LOCAL_INCLUDE_PATH."common.php");

#用户信息
include_once(_CONST_LOCAL_INCLUDE_PATH."session.include.php");


$quote = array();

$action = trim($_GET['action']);
$idx = intval($_GET['vote_id']);
$vuser = intval($_GET['vuser']);
if(is_loggedin())
{
	$user_id = intval($_SESSION['userid']);
	$quote['vote_time'] = string_sql(_CONST_TIMENOW);
}  
else{
	$user_id = 0;
}

if (!$user_id) {
	echo 1; 
} else if ($action == 'add' && $idx > 0) {
	#查找是否存在
	$rs = $database->queryFirst("SELECT `value` FROM user_votes WHERE user_id = " . $user_id . " AND vote_id = " . $idx);
	if(isset($rs['value'])){
		if($rs['value'] == 0) {
			$database->execute("UPDATE vote SET `add` = `add` + 1, `sub` = `sub` -1 WHERE id = " .$idx);
			$database->execute("REPLACE INTO user_votes (user_id, vote_id, vote_time, `value`) VALUES (".$user_id.", ".$idx.", ".$quote['vote_time']." ,1)");
			echo 3;
		}	
	}else{
		$database->execute("REPLACE INTO user_votes (user_id, vote_id, vote_time, `value`) VALUES (".$user_id.", ".$idx.", ".$quote['vote_time']." ,1)");
		$database->execute("UPDATE vote SET `add` = `add` + 1 WHERE id = " .$idx);
		echo 2;
	}
} else if ($action == 'sub' && $idx > 0) {
	#查找是否存在
	$rs = $database->queryFirst("SELECT `value` FROM user_votes WHERE user_id = " . $user_id . " AND vote_id = " . $idx);
	if(isset($rs['value'])){
		if($rs['value'] == 1) {
			$database->execute("UPDATE vote SET `add` = `add` - 1, `sub` = `sub` + 1 WHERE id = " .$idx);
			$database->execute("REPLACE INTO user_votes (user_id, vote_id, vote_time, `value`) VALUES (".$user_id.", ".$idx.", ".$quote['vote_time']." ,0)");
		echo 3;
		}
	}else{
		$database->execute("REPLACE INTO user_votes (user_id, vote_id, vote_time, `value`) VALUES (".$user_id.", ".$idx.", ".$quote['vote_time']." ,0)");
		$database->execute("UPDATE vote SET `sub` = `sub` + 1 WHERE id = " .$idx);
		echo 2;
	} 
}else if($action == 'rabbish' && $idx > 0) {
			$database->execute("UPDATE vote SET `rabbish` = `rabbish` + 1 WHERE id = " .$idx);
		echo 4;
}else if($action == 'close' && $idx > 0 && $vuser==$_SESSION['userid']) {
			$database->execute("UPDATE vote SET `lock` = 1 WHERE id = " .$idx);
		echo 5;
}else if($action == 'delete' && $idx > 0) {
	    $rs = $database->queryFirst("SELECT images,user_id FROM vote WHERE id=".$idx);
		$img = $rs["images"];
		$userid = $rs["user_id"];
		$imgpath = _CONST_PIC_PATH . 'vote/' . $userid . "/";
		@unlink($imgpath.$img);
		@unlink($imgpath."1_".$img);
		@unlink($imgpath."2_".$img);
		$database->execute("DELETE FROM vote_comment WHERE vote_id =".$idx);
        $database->execute("DELETE FROM vote WHERE id =".$idx);
		echo 5;
}
exit;
?>
